package org.pay.mch.order.ctrl;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.pay.mch.common.service.RpcCommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.pay.core.common.constant.Constant;
import org.pay.core.common.constant.MchConstant;
import org.pay.core.common.constant.RetEnum;
import org.pay.core.common.domain.PayPageRes;
import org.pay.core.common.domain.PayResponse;
import org.pay.core.entity.MchTradeOrder;
import org.pay.mch.common.ctrl.BaseController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author: yangshancheng
 * @date: 17/12/21
 * @description:
 */
@Controller
@RequestMapping(Constant.MCH_CONTROLLER_ROOT_PATH + "/trade_order")
@PreAuthorize("hasRole('"+ MchConstant.MCH_ROLE_NORMAL+"')")
public class MchTradeOrderController extends BaseController {

    @Autowired
    private RpcCommonService rpcCommonService;

    /**
     * 查询单条记录
     * @return
     */
    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String tradeOrderId = getStringRequired(param, "tradeOrderId");
        if(StringUtils.isBlank(tradeOrderId)) ResponseEntity.ok(PayResponse.build(RetEnum.RET_COMM_PARAM_ERROR));
        MchTradeOrder mchTradeOrder = rpcCommonService.rpcMchTradeOrderService.findByMchIdAndTradeOrderId(getUser().getId(), tradeOrderId);
        return ResponseEntity.ok(PayResponse.buildSuccess(mchTradeOrder));
    }

    /**
     * 订单记录列表
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        MchTradeOrder mchTradeOrder = getObject(param, MchTradeOrder.class);
        if(mchTradeOrder == null) mchTradeOrder = new MchTradeOrder();
        mchTradeOrder.setMchId(getUser().getId());
        int count = rpcCommonService.rpcMchTradeOrderService.count(mchTradeOrder);
        if(count == 0) ResponseEntity.ok(PayPageRes.buildSuccess());
        List<MchTradeOrder> mchTradeOrderList = rpcCommonService.rpcMchTradeOrderService.select(
                (getPageIndex(param) -1) * getPageSize(param), getPageSize(param), mchTradeOrder);
        return ResponseEntity.ok(PayPageRes.buildSuccess(mchTradeOrderList, count));
    }

}
